#include "recbox.h"
#include "ui_recbox.h"
#include "recboxitem.h"

#include <QJsonArray>
#include <QJsonObject>

recBox::recBox(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::recBox)
    , col(4)
    , row(1)
{
    ui->setupUi(this);

    connect(ui->btUp, &QPushButton::clicked, this, [=](){
        currentIndex = ++currentIndex % count;
        createRecBoxItem();
    });

    connect(ui->btDown, &QPushButton::clicked, this, [=](){
        currentIndex--;
        if(currentIndex < 0){ currentIndex = count;}
        createRecBoxItem();
    });
}

recBox::~recBox()
{
    delete ui;
}

void recBox::initRecBoxUi(QJsonArray& data, int row)
{

    if(2 == row)
    {
        this->row = row;
        col = 4;
    }
    else {
        ui->recListDown->hide();
    }

    imagelist = data;

    currentIndex = 0; //当前起始的组。
    count = data.size() / 4; //一共拥有的完整的组。
}

void recBox::createRecBoxItem()
{
    //清除所有元素
    QList<recBoxItem*> recItemListUp = ui->recListUp->findChildren<recBoxItem*>();
    for(auto& e : recItemListUp)
    {
        ui->recListUpLayout->removeWidget(e);
        delete(e);
    }
    QList<recBoxItem*> recItemListDown = ui->recListDown->findChildren<recBoxItem*>();
    for(auto& e : recItemListDown)
    {
        ui->recListDownLayout->removeWidget(e);
        delete(e);
    }

    //根据行列情况进行添加，从imageList这个jsonArray中取出文件路径
    if(row == 1)
        for(int i = currentIndex * 4; i < currentIndex * 4 + 4; i++)
        {
            recBoxItem* item = new recBoxItem(this);
            QJsonObject obj = imagelist[i].toObject();
            item->setRecBoxItemText(obj.value("text").toString());
            item->setMusicImage(obj.value("path").toString());

            ui->recListUpLayout->addWidget(item);
        }
    else
    {
        currentIndex = ++currentIndex % count;
        for(int i = currentIndex * 4; i < currentIndex * 4 + 4; i++)
        {
            recBoxItem* item = new recBoxItem(this);
            QJsonObject obj = imagelist[i].toObject();
            item->setRecBoxItemText(obj.value("text").toString());
            item->setMusicImage(obj.value("path").toString());

            ui->recListUpLayout->addWidget(item);
        }

        currentIndex = ++currentIndex % count;
        for(int i = currentIndex * 4; i < currentIndex * 4 + 4; i++)
        {
            recBoxItem* item = new recBoxItem(this);
            QJsonObject obj = imagelist[i].toObject();
            item->setRecBoxItemText(obj.value("text").toString());
            item->setMusicImage(obj.value("path").toString());

            ui->recListDownLayout->addWidget(item);
        }
    }
}
